package com.ai.controller.user;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.aop.AuthorityAnnotation;
import com.ai.aop.FunctionType;
import com.ai.common.controller.BaseController;
import com.ai.common.exception.BusinessException;
import com.ai.common.model.Pagination;
import com.ai.common.model.Result;
import com.ai.common.model.vo.BackOperatorVO;
import com.ai.common.utils.lang.string.StringUtils;
import com.ai.model.edu.cms.backoperator.BackendOperator;
import com.ai.model.edu.cms.backoperator.dto.BackendOperatorDTO;
import com.ai.model.edu.cms.backoperator.dto.OperatorRoleDTO;
import com.ai.model.edu.cms.backoperator.vo.BackendOperatorVO;
import com.ai.model.edu.cms.backoperator.vo.OperatorRoleVO;
import com.ai.service.cms.user.BackendOperatorService;
import com.ai.service.cms.user.OperatorRoleService;

/**
 * Class Name : BackOperatorController<br>
 * 
 * Description : 后台用户管理controller<br>
 * 
 * @author yangwb
 * @version $Revision$
 * @see
 *
 */
@Controller
public class BackOperatorController extends BaseController {
	
	private Log log = LogFactory.getLog(getClass());

    @Resource
    private BackendOperatorService backendOperatorService;

    @Resource
    private OperatorRoleService operatorRoleService;

    private BeanCopier COPIER = BeanCopier.create(BackOperatorVO.class, BackendOperatorVO.class, false);

    /**
     * Description ： 用户管理列表页面<br>
     * 
     * yangwb
     * 
     * @return
     * @since
     * 
     */
//    @AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_SYSTEM_BACKOPERATORMANAGER_TOPAGE })
    @RequestMapping("/backend/toUserControllerIndex")
    public String toUserControllerIndex(HttpServletRequest request) {
        return "/backend/toUserControllerIndex";
    }

    /**
     * Description ： 根据dto分页查询用户信息<br>
     * 
     * yangwb
     * 
     * @return
     * @since
     * 
     */
//    @AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_SYSTEM_BACKOPERATORMANAGER_TOPAGE })
    @RequestMapping("/backend/findBackendVOSPgByDTO")
    @ResponseBody
    public Pagination<BackendOperatorVO> findBackendVOSPgByDTO(BackendOperatorDTO backendOperatorDTO) {
        return backendOperatorService.findBackendVOSPgByDTO(backendOperatorDTO);
    }

    /**
     * Description ： 根据用户model 新增用户信息<br>
     * 
     * yangwb
     * 
     * @param backendOperator
     * @return
     * @since
     * 
     */
//    @AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_SYSTEM_BACKOPERATORMANAGER_ADDUSER })
    @RequestMapping("/backend/addBackendOperator")
    @ResponseBody
    public Result addBackendOperator(HttpServletRequest request, BackendOperator backendOperator) {
    	Result result = new Result();
        try {
        	 BackOperatorVO backOperatorVO = this.validateIsLogin(request);
             backendOperator.setCreateBy(backOperatorVO.getId());
             backendOperator.setUpdateBy(backOperatorVO.getId());
             result = backendOperatorService.addOrUpdateBackendOperator(backendOperator);
             result.setSuccess(true);
             result.setState(1);
		} catch(BusinessException e){
			log.error("新增用户信息业务异常" , e);
			result.setSuccess(false);
			result.setState(Integer.valueOf(e.getErrCode()));
			result.setMessage(e.getMessage());
		}catch (Exception e) {
			log.error("新增用户信息未知异常" , e);
			result.setSuccess(false);
			result.setState(-99);
			result.setMessage(e.getMessage());
		}
        return result;
    }

    /**
     * Description ： 根据用户model 编辑用户信息<br>
     * 
     * yangwb
     * 
     * @param backendOperator
     * @return
     * @since
     * 
     */
//    @AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_SYSTEM_BACKOPERATORMANAGER_UPDATEUSER })
    @RequestMapping("/backend/updateBackendOperator")
    @ResponseBody
    public Result updateBackendOperator(HttpServletRequest request, BackendOperator backendOperator) {
    	Result result = new Result();
        try {
	        BackOperatorVO backOperatorVO = this.validateIsLogin(request);
	        backendOperator.setCreateBy(backOperatorVO.getId());
	        backendOperator.setUpdateBy(backOperatorVO.getId());
	        result =  backendOperatorService.addOrUpdateBackendOperator(backendOperator);
	        result.setSuccess(true);
            result.setState(1);
        } catch(BusinessException e){
			log.error("更新用户信息业务异常" , e);
			result.setSuccess(false);
			result.setState(Integer.valueOf(e.getErrCode()));
			result.setMessage(e.getMessage());
		}catch (Exception e) {
			log.error("更新用户信息未知异常" , e);
			result.setSuccess(false);
			result.setState(-99);
			result.setMessage(e.getMessage());
		}
        return result;
    }

    /**
     * Description ： 根据dto更新用户信息状态<br>
     * 
     * yangwb
     * 
     * @return
     * @since
     * 
     */
//    @AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_SYSTEM_BACKOPERATORMANAGER_UPDATEUSERSTATUS })
    @RequestMapping("/backend/updateBackendUserStatusByDTO")
    @ResponseBody
    public Result updateBackendUserStatusByDTO(HttpServletRequest request, BackendOperatorDTO backendOperatorDTO) {
    	Result result = new Result();
    	try {
    		 BackOperatorVO backOperatorVO = this.validateIsLogin(request);
	        backendOperatorDTO.setUpdateBy(backOperatorVO.getId());
	        backendOperatorService.updateBackendUserStatusByDTO(backendOperatorDTO);
	        result.setSuccess(true);
	        result.setState(1);
		} catch(BusinessException e){
			log.error("业务异常" , e);
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			result.setState(Integer.valueOf(e.getErrCode()));
		}catch (Exception e) {
			log.error("未知异常" , e);
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			result.setState(-99);
		}
        return result;
    }

    /**
     * Description ： 删除用户<br>
     * 
     * yangwb
     * 
     * @return
     * @since
     * 
     */
//    @AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_SYSTEM_BACKOPERATORMANAGER_DELUSER })
    @RequestMapping("/backend/deleteBackOperatorByDTO")
    @ResponseBody
    public Result deleteBackOperatorByDTO(HttpServletRequest request, BackendOperatorDTO backendOperatorDTO) {
    	Result result = new Result();
    	try {
	        BackOperatorVO backOperatorVO = this.validateIsLogin(request);
	        backendOperatorDTO.setUpdateBy(backOperatorVO.getId());
	        backendOperatorService.deleteBackOperatorByDTO(backendOperatorDTO);
	        result.setSuccess(true);
	        result.setState(1);
		} catch(BusinessException e){
			log.error("业务异常" , e);
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			result.setState(Integer.valueOf(e.getErrCode()));
		}catch (Exception e) {
			log.error("未知异常" , e);
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			result.setState(-99);
		}
    	return result;
    }

    /**
     * Description ： 根据用户id查询当前用户设置了的用户角色关系信息<br>
     * 
     * yangwb
     * 
     * @param backOperatorId
     * @return
     * @since
     * 
     */
    @RequestMapping("/backend/findUserRole")
    @ResponseBody
    public List<OperatorRoleVO> findUserRole(Long backOperatorId) {
        OperatorRoleDTO userRoleDTO = new OperatorRoleDTO();
        userRoleDTO.setBackOperatorId(backOperatorId);
        return operatorRoleService.findUserRoleVOsByDTO(userRoleDTO);
    }

    /**
     * Description ： 保存用户角色关系信息<br>
     * 
     * yangwb
     * 
     * @param request
     * @param backendOperatorDTO
     * @return
     * @since
     * 
     */
//    @AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_SYSTEM_BACKOPERATORMANAGER_SAVEUSERROLE })
    @RequestMapping("/backend/saveBackUserRoles")
    @ResponseBody
    public Result saveBackUserRoles(HttpServletRequest request, Long backOperatorId, String addRoleIds, String delRoleIds) {
    	Result result = new Result();
    	try {
    		 BackOperatorVO backOperatorVO = this.validateIsLogin(request);
    	     backendOperatorService.addAndDelBackOperatorRole(backOperatorVO.getId(), backOperatorId, addRoleIds, delRoleIds);
    	     result.setSuccess(true);
 	         result.setState(1);
    	} catch(BusinessException e){
			log.error("业务异常" , e);
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			result.setState(Integer.valueOf(e.getErrCode()));
		}catch (Exception e) {
			log.error("未知异常" , e);
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			result.setState(-99);
		}
       
        return result;
    }

    /**
     * Description ： 用户信息管理页面<br>
     * 
     * yangwb
     * 
     * @return
     * @since
     * 
     */
    //@AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_OPERATOR_MYUSERINFO })
    @RequestMapping("/backend/toUserInfo")
    public String toUserInfo(HttpServletRequest request) {
        Long id = this.getBackendOperator(request).getId();
        BackendOperatorVO myBackendOperatorVO = backendOperatorService.findBackendOperatorVOById(id);
        request.setAttribute("myBackendOperatorVO", myBackendOperatorVO);
        return "/backend/userInfo";
    }

    /**
     * Description ： 根据用户model 新增or编辑用户信息<br>
     * 
     * yangwb
     * 
     * @param backendOperator
     * @return
     * @since
     * 
     */
//    @AuthorityAnnotation(functionType = { FunctionType.UNICOM_BACKEND_OPERATOR_UPDATE_MYUSERINFO })
    @RequestMapping("/backend/updateMyBackendOperator")
    @ResponseBody
    public Result updateMyBackendOperator(HttpServletRequest request, BackendOperatorDTO backendOperatorDTO) {
    	Result result = new Result();
    	try {
    		BackOperatorVO backOperatorVO = this.validateIsLogin(request);
            BackendOperatorVO backendOperatorVO = new BackendOperatorVO();
            COPIER.copy(backOperatorVO, backendOperatorVO, null);
            backendOperatorDTO.setUpdateBy(backOperatorVO.getId());
            backendOperatorService.updateMyBackendOperator(backendOperatorDTO, backendOperatorVO);
            result.setSuccess(true);
            result.setState(1);
    	} catch(BusinessException e){
			log.error("业务异常" , e);
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			result.setState(Integer.valueOf(e.getErrCode()));
		}catch (Exception e) {
			log.error("未知异常" , e);
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			result.setState(-99);
		}
        return result;
    }
    
    @RequestMapping("/backend/queryBackendOperatorByName")
    @ResponseBody
    public Result queryBackendOperatorByName(HttpServletRequest request, String term) {
        Result result = new Result(true);
        if(StringUtils.isNotBlank(term)){
            List<BackendOperatorVO> operatorList = backendOperatorService.findOperatorListByName(StringUtils.strip(term));
            if(CollectionUtils.isEmpty(operatorList)) {
                operatorList = new ArrayList<BackendOperatorVO>();
            }
            result.addAttribute("rows", operatorList);
        }
        return result;
    }
}
